﻿//----------------------------------------------------
//    版权：
//    作者：
//建立时间：2012-09-11 00:00:33
//    描述：
//----------------------------------------------------
using System;
using System.Data;
using System.Collections.Generic;
using System.Text;


using WinnerCMS.Common;
using WinnerCMS.Model;
using System.Linq;
using System.Data.Entity;

namespace WinnerCMS.Data
{
    /// <summary>
    /// 数据访问层CMS_Goods。
    /// </summary>
    public class GoodsDal
    {

        #region 是否存在
        /// <summary>
        /// 是否存在
        /// </summary>
        /// <param name="ContentTitle"></param>
        /// <returns></returns>
        public bool Exists(string ContentTitle)
        {
            using (Entities db = new Entities())
            {
                return db.Goods.Any(x => x.ContentTitle == ContentTitle);
            }
        }
        #endregion

        #region  添加数据
        /// <summary>
        /// 添加数据
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int Add(Goods model)
        {
            using (Entities db = new Entities())
            {
                var brand = db.Brands.FirstOrDefault(x => x.Id == model.BrandId);
                if (brand != null)
                    model.Brand = brand.Name;

                db.Goods.Add(model);

                db.SaveChangesAsync().Wait();
            }

            return model.Id;
        }
        #endregion

        #region  修改数据
        /// <summary>
        /// 修改数据
        /// </summary>
        /// <param name="model"></param>
        public void Edit(Goods model)
        {
            using (Entities db = new Entities())
            {
                var brand = db.Brands.FirstOrDefault(x => x.Id == model.BrandId);
                if (brand != null)
                    model.Brand = brand.Name;

                db.Goods.Attach(model);
                db.Entry(model).State = EntityState.Modified;
                db.SaveChangesAsync().Wait();
            }
        }
        #endregion

        #region  删除数据
        /// <summary>
        /// 删除
        /// </summary>
        public void Delete(int[] Ids)
        {
            using (Entities db = new Entities())
            {
                var q = from x in db.Goods where Ids.Contains(x.Id) select x;
                q.ToList().ForEach(x => db.Goods.Remove(x));

                db.SaveChangesAsync().Wait();
            }
        }

        #endregion

        #region  加载数据
        /// <summary>
        /// 加载数据
        /// </summary>
        public Goods GetInfo(int Id)
        {
            using (Entities db = new Entities())
            {
                return db.Goods.Where(x => x.Id == Id).FirstOrDefault();
            }
        }
        #endregion

        #region 图文列表
        /// <summary>
        ///  图文列表
        /// </summary>
        /// <param name="TopNo"></param>
        /// <returns></returns>
        public IList<Goods> PicGoods(int TopNo)
        {
            using (Entities db = new Entities())
            {
                var q = from x in db.Goods
                        where !x.IsDeleted && x.IsChecked && x.IncludePic
                        orderby x.Hits descending
                        select new { Id = x.Id, CategoryId = x.CategoryId, x.ContentTitle, x.Hits, x.UpdateTime, x.PriceMarket, x.PriceMember, x.PicUrl };

                return q.Take(TopNo).ToList().Select(x => new Goods() { Id = x.Id, CategoryId = x.CategoryId, ContentTitle = x.ContentTitle, Hits = x.Hits, UpdateTime = x.UpdateTime, PriceMarket = x.PriceMarket, PriceMember = x.PriceMember, PicUrl = x.PicUrl }).ToList();
            }
        }

        #endregion

        /// <summary>
        /// 热门产品
        /// </summary>
        /// <param name="topNo"></param>
        /// <param name="categoryId"></param>
        /// <returns></returns>
        public IList<Goods> HotGoods(int topNo, int categoryId)
        {
            using (Entities db = new Entities())
            {
                var q = from x in db.Goods
                        where !x.IsDeleted && x.IsChecked
                        orderby x.Hits descending
                        select new { x.Id, x.CategoryId, x.ContentTitle, x.Hits, x.UpdateTime, x.PriceMarket, x.PriceMember, x.PicUrl, x.TemplateFileName };
                if (categoryId > 0)
                {
                    q = q.Where(x => db.Categoryes.Where(y => y.Path.StartsWith("")).Select(z => z.Id).Contains(x.CategoryId));
                }

                return q.Take(topNo).ToList().Select(x => new Goods() { Id = x.Id, CategoryId = x.CategoryId, ContentTitle = x.ContentTitle, Hits = x.Hits, UpdateTime = x.UpdateTime, PriceMarket = x.PriceMarket, PriceMember = x.PriceMember, PicUrl = x.PicUrl, TemplateFileName = x.TemplateFileName }).ToList();
            }
        }
        /// <summary>
        /// 推荐产品
        /// </summary>
        /// <param name="topNo"></param>
        /// <returns></returns>
        public IList<Goods> EliteGoods(int topNo)
        {
            using (Entities db = new Entities())
            {
                var q = from x in db.Goods
                        where x.IsElite && !x.IsDeleted && x.IsChecked
                        orderby x.UpdateTime descending
                        select new { Id = x.Id, CategoryId = x.CategoryId, x.ContentTitle, x.Hits, x.UpdateTime, x.PriceMarket, x.PriceMember, x.PicUrl };

                return q.Take(topNo).ToList().Select(x => new Goods() { Id = x.Id, CategoryId = x.CategoryId, ContentTitle = x.ContentTitle, Hits = x.Hits, UpdateTime = x.UpdateTime, PriceMarket = x.PriceMarket, PriceMember = x.PriceMember, PicUrl = x.PicUrl }).ToList();

            }
        }



        /// <summary>
        /// 前台显示产品
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Goods PublicShow(int id)
        {
            using (Entities db = new Entities())
            {
                return db.Goods.FirstOrDefault(x => x.Id == id && !x.IsDeleted && x.IsChecked);
            }
        }

        /// <summary>
        /// 加载订单
        /// </summary>
        /// <param name="goodsId"></param>
        /// <param name="userName"></param>
        /// <returns></returns>
        public IList<ShoppingCart> ShowBuyUI(int goodsId, string userName)
        {
            //折扣率
            decimal Discount = 1;
            using (Entities db = new Entities())
            {
                var q = from x in db.Goods
                        where x.Id == goodsId
                        select new { GoodsId = x.Id, x.ContentTitle, Quantity = 1, x.Standard, x.PriceMember, PriceMember_Cuted = x.PriceMember * Discount };

                return q.ToList().Select(x => new ShoppingCart() { GoodsId = x.GoodsId, Quantity = x.Quantity, Shop = new Goods() { ContentTitle = x.ContentTitle, PriceMember = x.PriceMember, Standard = x.Standard }, PriceMember_Cuted = x.PriceMember_Cuted }).ToList();
            }
        }
        /// <summary>
        /// 从栏目读取品牌数据
        /// </summary>
        /// <param name="categoryId"></param>
        /// <returns></returns>
        public IList<Goods> CountBrandWhithCategoryId(int categoryId)
        {
            using (Entities db = new Entities())
            {
                var q = (from x in db.Goods
                         where x.Brand != "" && x.CategoryId == categoryId
                         group x by new { x.Brand, BrandID = x.BrandId } into g
                         select g.Key).ToList().Select(x => new Goods() { Brand = x.Brand, BrandId = x.BrandID });

                return q.ToList();
            }
        }

        #region 特价商品
        /// <summary>
        /// 特价商品
        /// </summary>
        /// <param name="topNo"></param>
        /// <returns></returns>
        public IList<Goods> GetTeJia(int topNo)
        {
            using (Entities db = new Entities())
            {
                return db.Goods.Where(x => !x.IsDeleted && x.IsChecked && x.IsSpecialPrice).ToList();
            }
        }
        #endregion

        #region 读取阅读过的商品

        /// <summary>
        /// 读取阅读过的商品
        /// </summary>
        /// <param name="topNo"></param>
        /// <param name="Ids"></param>
        /// <returns></returns>
        public IList<Goods> ReadedGoods(int topNo, int[] Ids)
        {
            using (Entities db = new Entities())
            {
                return db.Goods.Where(x => !x.IsDeleted && x.IsChecked && Ids.Contains(x.Id)).Take(topNo).ToList();
            }
        }
        #endregion

        /// <summary>
        /// 绑定分页
        /// </summary>
        /// <param name="brandId"></param>
        /// <param name="categoryIds"></param>
        /// <param name="sort"></param>
        /// <param name="orderBy"></param>
        /// <param name="pp"></param>
        /// <returns></returns>
        public IList<Goods> BindList(int? brandId, IEnumerable<int> categoryIds, string sort, string orderBy, PagingParam pp)
        {
            using (Entities db = new Entities())
            {
                var query = from x in db.Goods
                            where categoryIds.Contains(x.CategoryId) && !x.IsDeleted && x.IsChecked && x.PresentExp >= 0
                            select new { Id = x.Id, x.ContentTitle, x.Hits, x.UpdateTime, x.Stars, BrandID = x.BrandId, CategoryId = x.CategoryId, x.PicUrl, x.Brief, CssCategory = x.CssClass, x.PriceMarket, x.PriceMember  };
                if (brandId != null)
                {
                    query = query.Where(x => x.BrandID == brandId);
                }

                pp.RecordCount = query.Count();

                switch (sort)
                {
                    case "Hits":
                        if (orderBy == "DESC")
                        {
                            query = query.OrderByDescending(x => x.Hits).ThenByDescending(x => x.Id);
                        }
                        else
                        {
                            query = query.OrderBy(x => x.Hits).ThenByDescending(x => x.Id);
                        }
                        break;
                    //case "ContentState":
                    //    if (OrderBy == "DESC")
                    //    {
                    //        query = query.OrderByDescending(x => x.ContentState).ThenByDescending(x => x.Id);
                    //    }
                    //    else
                    //    {
                    //        query = query.OrderBy(x => x.ContentState).ThenByDescending(x => x.Id);
                    //    }
                    //    break;
                    case "PriceMember":
                        if (orderBy == "DESC")
                        {
                            query = query.OrderByDescending(x => x.PriceMember).ThenByDescending(x => x.Id);
                        }
                        else
                        {
                            query = query.OrderBy(x => x.PriceMember).ThenByDescending(x => x.Id);
                        }
                        break;
                    case "UpdateTime":
                        if (orderBy == "DESC")
                        {
                            query = query.OrderByDescending(x => x.UpdateTime).ThenByDescending(x => x.Id);
                        }
                        else
                        {
                            query = query.OrderBy(x => x.UpdateTime).ThenByDescending(x => x.Id);
                        }
                        break;
                    default:
                        throw new Exception("");
                }
                query = query.Skip(pp.Skip).Take(pp.PageSize);

                return query.ToList().Select(x => new Goods()
                {
                    Id = x.Id,
                    ContentTitle = x.ContentTitle,
                    Hits = x.Hits,
                    UpdateTime = x.UpdateTime,
                    Stars = x.Stars,
                    CategoryId = x.CategoryId,
                    PicUrl = x.PicUrl,
                    Brief = x.Brief,
                    CssClass = x.CssCategory,
                    PriceMarket = x.PriceMarket,
                    PriceMember = x.PriceMember

                }).ToList();
            }
        }

        #region 绑定简单内容
        /// <summary>
        /// 绑定简单内容
        /// </summary>
        /// <param name="pp"></param>
        /// <returns></returns>
        public IList<Goods> BindList(PagingParam pp)
        {
            using (Entities db = new Entities())
            {
                var query = from x in db.Goods
                            where !x.IsDeleted && x.IsChecked
                            orderby x.Id descending
                            select x;
                return query.Skip(pp.Skip).Take(pp.PageSize).ToList();
            }
        }
        /// <summary>
        /// 统计内容数量，配合“绑定简单内容”
        /// </summary>
        /// <returns></returns>
        public int Count()
        {
            using (Entities db = new Entities())
            {
                return db.Goods.Count(x => !x.IsDeleted && x.IsChecked);
            }
        }
        #endregion
    }
}